package com.ppc.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ppc.context.BaseContext;
import com.ppc.entity.Requirement;
import com.ppc.entity.Task;
import com.ppc.exception.BaseException;
import com.ppc.mapper.worker.WorkerMapper;
import com.ppc.mapper.worker.WorkerRequireMapper;
import com.ppc.pmatch.SKObj;
import com.ppc.pmatch.SKPO;
import com.ppc.result.PageResult;
import com.ppc.service.WorkerRequireService;
import com.ppc.utils.MatchServerUtil;
import com.ppc.utils.PMatchUtil;
import com.ppc.vo.RequireBroadVO;
import com.ppc.vo.RequirePageVO;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 工人需求接口实现
 *
 * @author Jeferry
 * @date 2023/12/20
 */
@Service
public class WorkerRequireServiceImpl implements WorkerRequireService {

  @Autowired
  private WorkerRequireMapper requireMapper;
  @Autowired
  private WorkerMapper workerMapper;

  /**
   * 查看广泛需求信息
   *
   * @param requireId 需求id
   * @return {@link RequireBroadVO}
   */
  @Override
  public RequireBroadVO quertBroadInformation(Long requireId) {
    RequireBroadVO require = requireMapper.quertBroadInformationById(requireId);
    if (require == null) {
      throw new BaseException("该需求不存在");
    }
    return require;
  }

  /**
   * 工人接受需求，将任务变成需求
   *
   * @param requireId 需求id
   */
  @Override
  public void acceptRequire(Long requireId) {
    //先进行信誉度判断
    Long currentId = BaseContext.getCurrentId();
    Integer workerCredit=workerMapper.getWorkerCredit(currentId);
    if(workerCredit<60){
      throw new BaseException("您的信誉度不足，无法接受该任务");
    }
    Requirement r = requireMapper.selectById(requireId);
    //设置期待完成的时间时deadline
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime expectedEndTime = r.getRequireDeadline();
    Long userId = BaseContext.getCurrentId();
    Long workerId = workerMapper.getCurrentWorkerId(userId);
    Task task = Task.builder()
        .requireId(r.getRequireId())
        .workerId(workerId)
        .taskStatus(0)
        .taskStartTime(now)
        .taskExpectedEndTime(expectedEndTime)
        .build();
    requireMapper.insertIntoTask(task);
    //任务变成订单，那么任务的属性就要变成匹配结束的状态
    requireMapper.changeRequireStatusIntoEnd(requireId);
  }

  /**
   * 根据自己标签查找匹配的需求
   *
   * @param page     页码
   * @param pageSize 页大小
   * @return {@link PageResult}
   */
  @Override
  public PageResult queryRequireByTags(Integer page, Integer pageSize) {
    Long userId = BaseContext.getCurrentId();
    Long workerId = workerMapper.getCurrentWorkerId(userId);
    //先根据工人的id找到工人的标签
    String tags = workerMapper.queryTagsById(workerId);
    //将标签字符转换成标签数组
    String[] tagArray = tags.split(",");
    for (int i = 0; i < tagArray.length; i++) {
      tagArray[i] = workerMapper.queryTagName(Integer.valueOf(tagArray[i]));
    }
    //用匹配工具类找到与之可以匹配的任务
    String sk1 = workerMapper.querySkOne(Math.toIntExact(workerId));
    String sk2 = workerMapper.querySkTwo(Math.toIntExact(workerId));
    SKPO SKpo = new SKPO(Math.toIntExact(workerId), sk1, sk2, LocalDateTime.now());
    SKObj SK;
    try {
      SK = PMatchUtil.SKPOtoSKObj(SKpo);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    List<Long> result = MatchServerUtil.PostMatch(SK, tagArray);
    System.out.println(result);
    //根据任务的id返回相应结果
    PageHelper.startPage(page, pageSize);
    Page<RequirePageVO> p = requireMapper.pageQuery(result);
    return new PageResult(p.getTotal(), p.getResult());
  }
}
